/*************************************************************
 * Title: SecurityHelper.java
 * Description: 
 * Author: Huang Shaobin
 * Email: shaobin.software@gmail.com
 * CreateTime: Feb 21, 2013 2:58:25 PM
 ************************************************************/
package snow.core.security;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import snow.core.security.annotations.Operation;
import snow.core.security.annotations.Resource;

/**
 *
 */
public class SecurityHelper {

	public static Operation getOperationFrom(final Method method) {
		return method == null ? null : method.getAnnotation(Operation.class);
	}

	public static Operator getOperatorFrom(Method method) {
		Operation operation = getOperationFrom(method);
		return operation == null ? null : operation.type();
	}

	public static List<Resource> getResourcesFrom(Class<?> targetClass, Method method) {
		List<Resource> resources = new ArrayList<Resource>(3);
		final Package pack = targetClass == null ? null : targetClass.getPackage();
		final Resource packResource = pack == null ? null : pack.getAnnotation(Resource.class);
		if (packResource != null) {
			resources.add(packResource);
		}
		final Resource classResource = targetClass == null ? null : targetClass.getAnnotation(Resource.class);
		if (classResource != null) {
			resources.add(classResource);
		}
		final Resource methodResource = method == null ? null : method.getAnnotation(Resource.class);
		if (methodResource != null) {
			resources.add(methodResource);
		}
		return resources;
	}

	public static List<Resource> getResourcesFrom(Object target, Method method) {
		return getResourcesFrom(target == null ? null : target.getClass(), method);
	}

	public static String getResourceUriFrom(Class<?> targetClass, Method method) {
		StringBuilder resourceUri = new StringBuilder(255);
		List<Resource> resources = getResourcesFrom(targetClass, method);
		if (CollectionUtils.isNotEmpty(resources)) {
			for (Resource resource : resources) {
				final String uri = resource == null ? null : resource.uri();
				resourceUri.append(StringUtils.isBlank(uri) ? "" : StringUtils.trim(uri));
			}
		}
		return resourceUri.toString();
	}

	public static String getResourceUriFrom(Object target, Method method) {
		return getResourceUriFrom(target == null ? null : target.getClass(), method);
	}
}
